<script>
import { defineComponent, h } from 'vue'
import { ElOption, ElOptionGroup } from 'element-plus'

export default defineComponent({
  name: 'SelectOptionsRenderer',
  props: {
    item: { type: Object, required: true }
  },
  methods: {
    renderOptions(options) {
      const componentsProps = this.item.componentProps || {}
      const labelAlias = componentsProps.props?.label || 'label'
      const keyAlias = componentsProps.props?.key || 'key'
      const valueAlias = componentsProps.props?.value || 'value'
      const optionGroupDefaultSlot = componentsProps.slots?.optionGroupDefault
      const optionDefaultSlot = componentsProps.slots?.optionDefault

      return options.map(option => {
        if (option.options && option.options.length) {
          // 有子选项，渲染分组
          if (optionGroupDefaultSlot) {
            // 如果有自定义分组插槽，调用它
            return optionGroupDefaultSlot(option)
          } else {
            return h(
              ElOptionGroup,
              { label: option[labelAlias], key: option[keyAlias] },
              {
                default: () => this.renderOptions(option.options)
              }
            )
          }
        } else {
          // 普通选项
          return h(
            ElOption,
            {
              key: option[keyAlias],
              label: option[labelAlias],
              value: option[valueAlias]
            },
            {
              default: () => (optionDefaultSlot ? optionDefaultSlot(option) : null)
            }
          )
        }
      })
    }
  },
  render() {
    const componentsProps = this.item.componentProps || {}
    const options = componentsProps.options || []
    return h('div', this.renderOptions(options))
  }
})
</script>
